package handler

import (
	"context"
	"github.com/gin-gonic/gin"
	"group-buying/global"
	"group-buying/internal/api/request"
	user1 "group-buying/internal/proto/user"
	"group-buying/pkg"
	"net/http"
	"path/filepath"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "获取文件失败",
		})
		return
	}
	if file.Size > 20*1024*1024 {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "文件内存过大",
		})
		return
	}
	ext := filepath.Ext(file.Filename)
	if !(ext == ".png" || ext == ".jpe" || ext == "jpeg" || ext == ".mp4") {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "文件内存过大",
		})
		return
	}
	uploadFile, err := pkg.UploadFile(file, file.Filename)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "文件上传失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "文件上传成功",
		"data": uploadFile,
	})
}

func GroupList(c *gin.Context) {
	var req request.GroupListReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能空",
		})
		return
	}
	list, err := global.UserClient.GroupList(context.Background(), &user1.GroupListReq{
		Name:     req.Name,
		Page:     int32(req.Page),
		PageSize: int32(req.PageSize),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "列表展示失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "列表展示成功",
		"data": list,
	})
}

func CreateGroup(c *gin.Context) {
	var req request.CreateGroupReq
	err := c.ShouldBind(&req)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "数据不能空",
		})
		return
	}
	_, err = global.UserClient.CreatGroup(context.Background(), &user1.CreatGroupReq{
		Name:   req.Name,
		State:  int32(req.State),
		Num:    int32(req.Num),
		UserId: int32(req.UserId),
	})
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": http.StatusBadRequest,
			"msg":  "拼团失败",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "拼团成功",
	})
}
